# coding = utf-8

'''
分析数据中，纹理变化明显，但是不是肿瘤区域的大小
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math
from skimage import measure

def find_data_by_index(case_id, origion_id, index):
    big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
    big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
    big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
    big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
    big_image[big_image <= -200] = -200
    big_image[big_image > 250] = 250
    big_image = (big_image + 200) / 450
    big_image = big_image[index]
    big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
    big_liver = big_liver[index]
    big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
    big_tumor = big_tumor[index]
    return (big_image, big_liver, big_tumor)

def garbor_filter(image):
    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters3 = []
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi/6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi / 2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    result3 = cv2.equalizeHist(result3)


    return result3

def main_for_show():
    (big_image, big_liver, tumor) = find_data_by_index(case_id=77, origion_id="0762", index=199)

    tumor[tumor > 0] = 1
    big_tumor = tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    liver = big_image * big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    garbor_result = garbor_filter(big_image * big_liver)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=5)
    data[data <= 200] = 0
    data[data > 200] = 1
    liver_t = np.zeros(data.shape)
    temp = big_image * big_liver
    liver_t += (temp * data)
    liver_t += (temp * (1 - data) * 1.2)
    liver_t = liver_t / 1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    [data_labels, num] = measure.label(data, return_num=True)

    for i in np.unique(data_labels):
        if (data_labels == i).sum() < 1000 or i == 0:
            continue
        temp = np.zeros(data_labels.shape)
        temp[data_labels == i] = 1
        fp = 1 - float((big_tumor[temp == 1] > 0).sum()) / float((temp == 1).sum())
        print(i, format(fp, ".2f"))

    plt.subplot(2, 2, 1)
    plt.title("origion image")
    plt.imshow(liver)
    plt.subplot(2, 2, 2)
    plt.title("gabor enhance")
    plt.imshow(liver_t)
    plt.subplot(2, 2, 3)
    plt.title("mask")
    plt.imshow(data, cmap="gray")
    plt.subplot(2, 2, 4)
    plt.title("region")
    plt.imshow(data_labels)
    plt.show()

def find_data(case_id, origion_id):
    big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
    big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
    big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
    big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
    big_image[big_image <= -200] = -200
    big_image[big_image > 250] = 250
    big_image = (big_image + 200) / 450
    big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
    big_liver[big_liver > 0] = 1
    big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
    big_tumor[big_tumor > 0] = 1
    return (big_image, big_liver, big_tumor)

def main():

    case_id_2_origion_id = {}
    with open("../Others/case_id_2_origion", "r") as file:
        for line in file:
            line = line.strip().split(" ")
            case_id_2_origion_id[int(line[0])] = line[1]

    for i in range(60, 80):
        print("*"*20, i, "*"*2, case_id_2_origion_id[i], "*"*20)
        (image, liver, tumor) = find_data(case_id=i, origion_id=case_id_2_origion_id[i])
        for j in range(image.shape[0]):
            image_temp = image[j]
            liver_temp = liver[j]
            tumor_temp = tumor[j]
            if liver_temp.sum() == 0:
                continue

            garbor_result = garbor_filter(image_temp * liver_temp)
            data = cv2.medianBlur((255 - garbor_result) * liver_temp, ksize=5)
            data[data <= 200] = 0
            data[data > 200] = 1

            [data_labels, num] = measure.label(data, return_num=True)
            for t in np.unique(data_labels):
                if (data_labels == t).sum() < 1000 or t == 0:
                    continue
                temp = np.zeros(data_labels.shape)
                temp[data_labels == t] = 1
                fp = 1 - float((tumor_temp[temp == 1] > 0).sum()) / float((temp == 1).sum())
                if fp >= 0.5:
                   print(i, case_id_2_origion_id[i], j, t, format(fp, ".2f"))






if __name__ == '__main__':
    main()
    #main_for_show()